const express = require('express');
const router = express.Router();
const random = require('string-random');
const chinaTime = require('china-time');
const bodyParser = require('body-parser');
const loginSQL = require('../../db/loginSQL')
const replySQL = require('../../db/replySQL')

router.post('/addreply', bodyParser.json(), (req, res) => {
    // 检查用户ID是否为空
    if (!req.body["userID"]
        || typeof req.body["userID"] != "number") {
        res.json({
            err: 1,
            message: '用户ID为空'
        })
    } else if (req.body["postID"] == undefined
        || req.body["postID"] == null
        || typeof req.body["postID"] != "number") {
        res.json({
            err: 1,
            message: '主帖为空'
        })
    } else if (!req.body["content"]
        || typeof req.body["content"] != "string"
        || !req.body["content"].length) {
        res.json({
            err: 1,
            message: '回帖内容为空'
        })
    } else if (req.body["isAnnouncement"] == undefined
        || req.body["isAnnouncement"] == null
        || typeof req.body["isAnnouncement"] != "number") {
        res.json({
            err: 1,
            message: '帖子类型为空' + req.body["isAnnouncement"]
        })
    } else {
        let userID = req.body["userID"];
        let username = req.body["username"];
        let postID = req.body["postID"];
        let content = req.body["content"];
        let replyTime = chinaTime('YYYYMMDD');
        let isAnnouncement = req.body["isAnnouncement"];

        loginSQL.getByID(userID, (result) => {
            var userStatus = result[0].userStatus
            if (userStatus == 0) {
                res.json({
                    err: 3,
                    message: '用户被封禁'
                })
            }
            else {
                replySQL.addFile(content, (filename) => {
                    replySQL.addreply(userID, postID, isAnnouncement, filename, replyTime, (replyID) => {
                        res.json({
                            err: 200,
                            message: '回帖成功',
                            userID,
                            username,
                            postID,
                            replyTime,
                        })
                    })
                })
            }
        })
    }
})

module.exports = router;